package com.stlm2.dems.user.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.user.entity.IsValid;
import com.stlm2.dems.user.entity.PermissionType;
import com.stlm2.dems.entity.User;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.user.entity.SystemPrivilege;
import com.stlm2.dems.user.dao.SystemPrivilegeDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("systemPrivilegeService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class SystemPrivilegeService extends BaseServiceImpl<SystemPrivilege> {

	@Resource
	private SystemPrivilegeDao systemPrivilegeDao;
	@Resource
	private UserDao userDao;
	@Resource
	private Memcached memcached;

	@Override
	protected BaseDao <SystemPrivilege> getDao() {
		return systemPrivilegeDao;
	}
	/*
	*添加系统资源
	*  @param  token
	*  @param   cnName:名称（中文简称）
	*  @param  permissionName :权限名
	*  @param  url : url
	*  @param  permissionType: 资源类型1：URL 2：子菜单 3:按钮 4：父菜单
	*  @param  permission: 初始化权限
	*  @param  superId ：父类ID
	*  @param  explain ：资源说明
	 */
	public  String add(ModelMap map,String token,String cnName,String  permissionName,String url,String permissionType,
					   String permission ,String superId,String explain,String number){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		if (StringUtils.isEmpty(cnName)) {
			return CodeContent.getModelByCode(0, "名称不能为空", map);
		}
		if (StringUtils.isEmpty(permissionName)) {
			return CodeContent.getModelByCode(0, "权限名不能为空", map);
		}
		if (StringUtils.isEmpty(permissionType)) {
			return CodeContent.getModelByCode(0, "资源类型不能为空", map);
		}
		if (StringUtils.isEmpty(superId)) {
			return CodeContent.getModelByCode(0, "父类ID不能为空", map);
		}
		if (!NumberUtils.isNumber(superId)) {
			return CodeContent.getModelByCode(0, "父类ID不为数字", map);
		}
		if (StringUtils.isEmpty(explain)) {
			return CodeContent.getModelByCode(0, "资源说明不能为空", map);
		}
		if (!NumberUtils.isNumber(number)) {
			return CodeContent.getModelByCode(0, "序号不能为空", map);
		}
		if(PermissionType.getByIntValue(Integer.parseInt(permissionType))==null){
			return CodeContent.getModelByCode(0, "资源类型不正确", map);
		}
		if(PermissionType.getByIntValue(Integer.parseInt(permissionType)).equals(PermissionType.URL)){
			if (StringUtils.isEmpty(url)) {
				return CodeContent.getModelByCode(0, "选择URL类型时，URL不能为空", map);
			}
			if (StringUtils.isEmpty(permission)) {
				return CodeContent.getModelByCode(0, "选择URL类型时，权限必须初始化", map);
			}
			if(!superId.equals("0")){
				return CodeContent.getModelByCode(0, "选择URL类型时，父类ID必须为0", map);
			}
		}
		if(PermissionType.getByIntValue(Integer.parseInt(permissionType)).equals(PermissionType.SuperMenu)){
			if(!superId.equals("0")){
				return CodeContent.getModelByCode(0, "选择父菜单类型时，父类ID必须为0", map);
			}
		}
		if(!superId.equals("0")){
			SystemPrivilege superSystemPrivilege=systemPrivilegeDao.getById(Integer.parseInt(superId));
			if(superSystemPrivilege==null){
				return CodeContent.getModelByCode(0, "父类ID不正确", map);
			}
			if(PermissionType.getByIntValue(Integer.parseInt(permissionType)).equals(PermissionType.Menu)){
				if(!superSystemPrivilege.getPermissionType().equals(PermissionType.SuperMenu)){
					return CodeContent.getModelByCode(0, "选择子菜单类型时，父菜单ID不正确", map);
				}
			}
			if(PermissionType.getByIntValue(Integer.parseInt(permissionType)).equals(PermissionType.Button)){
				if(!superSystemPrivilege.getPermissionType().equals(PermissionType.Menu)){
					return CodeContent.getModelByCode(0, "选择按钮类型时，父菜单ID不正确", map);
				}
			}
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"addSystemPrivilege");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在5秒后重试", map);
		}else {
			memcached.set(loginUser.getId()+"addSystemPrivilege",5,"1");
		}
		SystemPrivilege systemPrivilege = new SystemPrivilege();
		systemPrivilege.setCnName(cnName.trim());
		systemPrivilege.setPermissionName(permissionName.trim());
		systemPrivilege.setUrl(url);
		systemPrivilege.setPermissionType(PermissionType.getByIntValue(Integer.parseInt(permissionType)));
		systemPrivilege.setPermission(permission);
		systemPrivilege.setSuperId(Integer.parseInt(superId));
		systemPrivilege.setExplains(explain);
		systemPrivilege.setIsValid(IsValid.Normal);
		systemPrivilege.setCreateTime(new Date());
		systemPrivilege.setNumber(Integer.parseInt(number));
		systemPrivilegeDao.add(systemPrivilege);
		return CodeContent.getModelByCode(1,"",map);

	}
/*
	*查找系统资源
	*  @param  token
	*  @param   permissionTypeValue:资源类型值1：URL 2：子菜单 3:按钮 4：父菜单
	*  @param  superId :父类ID
	*  @param  isValidValue :状态值 1：正常 2：无效
	 */
public  String search(ModelMap map,String page,String token,String permissionTypeValue,String superId,String isValidValue){
	PageView pageview =new  PageView();
	int pageNo = 1;
	int pageSize=20;
	if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
		pageNo = NumberUtils.toInt(page);
	}
	if (StringUtils.isEmpty(token)) {
		return CodeContent.getModelByCode(-1, "", map);
	}
	User loginUser = userDao.getByToken(token);
	if (loginUser == null) {
		return CodeContent.getModelByCode(-1, "", map);
	}
	SystemPrivilege systemPrivilege =new SystemPrivilege();
	if(NumberUtils.isNumber(isValidValue)){
		systemPrivilege.setIsValidValue(Integer.parseInt(isValidValue));
	}
	if(NumberUtils.isNumber(permissionTypeValue)){
		systemPrivilege.setPermissionTypeValue(Integer.parseInt(permissionTypeValue));
	}
	if (NumberUtils.isNumber(superId)) {
		systemPrivilege.setSuperId(Integer.parseInt(superId));
	}
	pageview=systemPrivilegeDao.queryPageView2(pageNo, pageSize,systemPrivilege);

	if (pageview != null){
		map.put("datas",convertList(pageview.getRecords()));
		map.put("recordsTotal", pageview.getRowCount());
		map.put("totalPage", pageview.getPageCount());
		map.put("pageNow", pageview.getPageNow());
		map.put("code",1);
		map.put("msg","success");
	}
	return  new JSONObject(map).toString();

}

	public List<ModelMap> convertList(List<SystemPrivilege> systemPrivilegeList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelList(systemPrivilege);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelList(SystemPrivilege systemPrivilege) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		ModelMap model = new ModelMap();
		model.put("isValidValue",systemPrivilege.getIsValidValue());
		model.put("isValid",systemPrivilege.getIsValid().toString());
		model.put("id",systemPrivilege.getId());
		model.put("permissionTypeValue",systemPrivilege.getPermissionTypeValue());
		model.put("permissionType",systemPrivilege.getPermissionType().toString());
		if(systemPrivilege.getPermission()!=null){
			model.put("permission",systemPrivilege.getPermission());
		}else {
			model.put("permission","");
		}
		model.put("cnName",systemPrivilege.getCnName());
		model.put("createTime",formatter.format(systemPrivilege.getCreateTime()));
		model.put("permissionName",systemPrivilege.getPermissionName());
		model.put("explain",systemPrivilege.getExplains());
		if(systemPrivilege.getUrl()!=null){
			model.put("url",systemPrivilege.getUrl());
		}else {
			model.put("url","");
		}
		if(systemPrivilege.getSuperId()!=0){
			SystemPrivilege superSystemPrivilege =systemPrivilegeDao.getById(systemPrivilege.getSuperId());
			model.put("superSystemPrivilege",superSystemPrivilege.getCnName());
		}else {
			model.put("superSystemPrivilege","");
		}

		return  model;
	}

	/*
	*zlq
	* 根据资源类型获取父类ID列表（仅限于2:子菜单 3 ：按钮）
	* @param  permissionTypeValue ：资源类型值
	 */
	public String getSuperIdList(ModelMap map,String permissionTypeValue){
		SystemPrivilege systemPrivilege =new SystemPrivilege();
		List <SystemPrivilege> systemPrivilegeArrayList=new ArrayList<SystemPrivilege>();
		if(permissionTypeValue.equals("2")){
			systemPrivilege.setPermissionType(PermissionType.SuperMenu);
			systemPrivilege.setIsValid(IsValid.Normal);
			systemPrivilegeArrayList=systemPrivilegeDao.queryPageView(-1,-1,systemPrivilege).getRecords();
		}
		if(permissionTypeValue.equals("3")){
			systemPrivilege.setPermissionType(PermissionType.Menu);
			systemPrivilege.setIsValid(IsValid.Normal);
			systemPrivilegeArrayList=systemPrivilegeDao.queryPageView(-1,-1,systemPrivilege).getRecords();
		}
		map.put("datas",convertSuperIds(systemPrivilegeArrayList));
		map.put("code",1);
		map.put("msg","success");
		return  new JSONObject(map).toString();


	}
	public List<ModelMap> convertSuperIds(List<SystemPrivilege> systemPrivilegeList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelSuperIds(systemPrivilege);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelSuperIds(SystemPrivilege systemPrivilege) {
		ModelMap model = new ModelMap();
		model.put("id",systemPrivilege.getId());
		if(systemPrivilege.getPermissionType().equals(PermissionType.URL)){
			model.put("cnName",systemPrivilege.getCnName() + "--"+systemPrivilege.getPermission());
		}else {
			model.put("cnName",systemPrivilege.getCnName());
		}

		return  model;
	}

	/*
	*zlq
	*系统权限树形图
	* @param  token
	*
	 */
	public String getPrivilegeTree(ModelMap map ,String token){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		SystemPrivilege superMenu=new SystemPrivilege();
		superMenu.setPermissionType(PermissionType.SuperMenu);
		superMenu.setIsValid(IsValid.Normal);
		List<SystemPrivilege> superMenuList=systemPrivilegeDao.queryPageView(-1,-1,superMenu).getRecords();
		SystemPrivilege urlPrivilege=new SystemPrivilege();
		urlPrivilege.setPermissionType(PermissionType.URL);
		urlPrivilege.setIsValid(IsValid.Normal);
		List<SystemPrivilege> urlList=systemPrivilegeDao.queryPageView(-1,-1,urlPrivilege).getRecords();

		map.put("superMenuList",convertsuperMenuList(superMenuList));
		map.put("urlList",convertSuperIds(urlList));
		map.put("code",1);
		map.put("msg","success");
		return  new JSONObject(map).toString();
	}
	public List<ModelMap> convertsuperMenuList(List<SystemPrivilege> systemPrivilegeList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelsuperMenu(systemPrivilege);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelsuperMenu(SystemPrivilege systemPrivilege) {
		ModelMap model = new ModelMap();
		model.put("superId",systemPrivilege.getId());
		model.put("superCnName","(" + systemPrivilege.getNumber() +")-" + systemPrivilege.getCnName());
		SystemPrivilege menu=new SystemPrivilege();
		menu.setSuperId(systemPrivilege.getId());
		menu.setIsValid(IsValid.Normal);
		List<SystemPrivilege> menuList=systemPrivilegeDao.queryPageView(-1,-1,menu).getRecords();
		model.put("menuList",convertMenuList(menuList));
		return  model;
	}
	public List<ModelMap> convertMenuList(List<SystemPrivilege> systemPrivilegeList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelMenu(systemPrivilege);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelMenu(SystemPrivilege systemPrivilege) {
		ModelMap model = new ModelMap();
		model.put("MenuId",systemPrivilege.getId());
		model.put("MenuCnName","(" + systemPrivilege.getNumber() +")-" + systemPrivilege.getCnName());
		SystemPrivilege button=new SystemPrivilege();
		button.setSuperId(systemPrivilege.getId());
		button.setIsValid(IsValid.Normal);
		List<SystemPrivilege> buttonList=systemPrivilegeDao.queryPageView(-1,-1,button).getRecords();
		model.put("buttonList",convertButtonList(buttonList));
		return  model;
	}
	public List<ModelMap> convertButtonList(List<SystemPrivilege> systemPrivilegeList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelButton(systemPrivilege);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelButton(SystemPrivilege systemPrivilege) {
		ModelMap model = new ModelMap();
		model.put("buttonId",systemPrivilege.getId());
		model.put("buttonCnName","(" + systemPrivilege.getNumber() +")-" + systemPrivilege.getCnName());
		return  model;
	}


}